/*
 * Server.cpp
 *
 *  Created on: Oct 27, 2012
 *      Author: lucas
 */

#include "Server.h"
#include "Client.h"
#include <sstream>
#include <iostream>
#include "ServerEventFactory.h"
#include "../common/Event.h"

Server::Server(unsigned int port) : listening_t(port, *this),event_t(*this){

}



void Server::agregarCliente(Client* ct) {
	clientes.push_back(ct);
}

void Server::quitarClientesDesconectados() {
	std::vector<Client*>::iterator it;
	for (it = clientes.begin(); it != clientes.end(); it++) {
		if (!((*it)->isConnected())) {
			(*it)->join();
			delete (*it);
			it = clientes.erase(it);
		}
	}
}

void Server::run() {
	listening_t.iniciar();
	event_t.iniciar();
}

void Server::stop() {
	std::vector<Client*>::iterator it;

	listening_t.parar();
	listening_t.join();
	for (it = clientes.begin(); it != clientes.end(); ++it) {
		if ((*it)->isConnected())
			(*it)->disconnect();
		(*it)->join();
		delete (*it);
	}
	clientes.clear();
}


void Server::addRequest(std::string request, Client& client) {
	Event* e;
	e = new Event(request, client);
	eventQueue.push(e);
}

Event* Server::receiveEvent() {
	Event* event;
	event = eventQueue.pop();
	return event;
}

Server::~Server() {
}
